﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Storage;
using SharpShare.Storage.Security;

namespace SharpShare.Afp.Protocol.Handlers {
    internal class AfpGetExtAttributeRequestHandler : IAfpRequestHandler {
        public byte CommandCode {
            get { return 69; }
        }

        public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) {
            requestStream.ReadPadding();

            ushort volumeId = requestStream.ReadUInt16();
            uint directoryID = requestStream.ReadUInt32();
            AfpExtendedAttributesBitmap fileBitmap = requestStream.ReadEnum<AfpExtendedAttributesBitmap>();
            long offset = requestStream.ReadInt64();
            long reqCount = requestStream.ReadInt64();
            int maxReplySize = requestStream.ReadInt32();
            IAfpVolume volume;
            IStorageItem item = requestStream.ReadPathAndFind(session, volumeId, directoryID, out volume).DemandExists();

            item.GetEffectiveAccess(session).DemandRight(StorageAccessRight.GetMetadata);

            requestStream.ReadPadding();

            string name = requestStream.ReadUTF8String();
            string useName = (AfpSetExtAttributeRequestHandler.CustomMetadataNamePrefix + name);
            byte[] data = item.GetMetadata(useName);

            if (data == null) {
                return AfpResultCode.FPMiscErr;
            }

            responseStream.WriteEnum(fileBitmap);
            responseStream.WriteInt32(data.Length);

            if (maxReplySize != 0) {
                if (maxReplySize < data.Length) {
                    return AfpResultCode.FPParamErr;
                }

                responseStream.WriteBytes(data);
            }

            return AfpResultCode.FPNoErr;
        }
    }
}
